<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Controller class
 */
abstract class Controller {
	private static $_instance = null;
	private static $_class_name = '';
	
	public static function &instance() {
		if (!isset(self::$_instance) && !empty(self::$_class_name)) {
			self::$_instance = new self::$_class_name;
		}

		return self::$_instance;
	}

	private function __construct() {}

	public function __clone() {
		throw new Node_Exception('Can`t clone singletone object');
	}

	public static function init($class_name) {
		self::$_class_name = $class_name;
	}
	
	public static function find($current, $default) {
		$result = array(
			'name' => '',
			'default' => true,
			'found' => false
		);

		$current_class = Node::CONTROLLER_PREFIX . ucfirst(trim(strtolower($current)));
		if (!empty($current)) {
			$file_name = Node::classNameToFileName($current_class);
			$file_path = Node::findFile('classes', $file_name);
			if ($file_path) {
				$result['name'] = self::fixName($current_class);
				$result['default'] = false;
				$result['found'] = true;
			}
		}

		// If controller not loaded then load default controller
		$default_class = Node::CONTROLLER_PREFIX . ucfirst(trim(strtolower($default)));
		if (!$result['found'] && ($default_class != $current_class)) {
			$file_name = Node::classNameToFileName($default_class);
			$file_path = Node::findFile('classes', $file_name);
			if ($file_path) {
				$result['name'] = self::fixName($default_class);
				$result['default'] = true;
				$result['found'] = true;
			}
		}

		return $result;
	}

	public static function fixName($str) {
		$str = strtolower($str);
		$arr = explode('_', $str);
		$arr = array_map('ucfirst', $arr);
		$str = implode('_', $arr);
		return $str;
	}
}
